<script setup lang="ts">
import {
  ConfigMap,
  Container,
  PersistentVolume,
  PersistentVolumeClaim,
  randVolumeName,
  Secret,
  StorageType,
  Volume
} from "@/views/domain/kubeHud/api/k8s";
import { computed, onMounted, reactive, ref } from "vue";
import KSection from "@/views/domain/kubeHud/views/components/k-section/index.vue";
import KSegment from "@/views/domain/kubeHud/views/components/k-segment/index.vue";
import KoDataItem from "@/views/domain/kubeHud/views/components/ko-data-item/index.vue";
import KDescItem from "@/views/domain/kubeHud/views/components/k-section/KDescItem.vue";
import koVolumeMount from "@/views/domain/kubeHud/views/components/ko-workloads/ko-spec/ko-volume-mount.vue";
import PVCSelector from "../../storage/pvc/widgets/PVCSelector.vue";
import ConfigMapSelector from "../../configuration/config-maps/widgets/ConfigMapSelector.vue";
import SecretSelector from "../../configuration/secrets/widgets/SecretSelector.vue";
import { isEmpty } from "@pureadmin/utils";

type Prop = {
  storageType?: StorageType;
  namespace: string;
};

const props = defineProps<Prop>();

const volume = defineModel<Volume>("volume");
const containers = defineModel<Container[]>("containers");

const pvcModel = ref<PersistentVolumeClaim>();
const cfgMapModel = ref<ConfigMap>();
const secretModel = ref<Secret>();

const _volumeType = ref<StorageType | "Unknown">("Unknown");

const volumeName = (): string => {
  if (!volume.value.name || volume.value.name === "") {
    return randVolumeName();
  }
  return volume.value.name;
};

const volumeType = computed({
  get: () => _volumeType.value,
  set: vt => {
    switch (vt) {
      case "PersistentVolumeClaim":
        volume.value = {
          name: volumeName(),
          persistentVolumeClaim: { claimName: "" }
        };
        break;
      case "ConfigMap":
        volume.value = {
          name: volumeName(),
          configMap: { name: "", items: [] }
        };
        break;
      case "Secret":
        volume.value = {
          name: volume.value.name ?? randVolumeName(),
          secret: { secretName: "", items: [] }
        };
        break;
      case "EmptyDir":
        volume.value = {
          name: volumeName(),
          emptyDir: {}
        };
        break;
      case "HostPath":
        volume.value = {
          name: volumeName(),
          hostPath: {}
        };
        break;
    }
    _volumeType.value = vt;
    console.log("on change volumeType", vt, volume.value);
  }
});
const volumeTypeSelections = [
  { value: "PersistentVolumeClaim", label: "持久卷声明" },
  { value: "ConfigMap", label: "配置字典" },
  { value: "Secret", label: "密钥字典" },
  { value: "EmptyDir", label: "临时卷" },
  { value: "HostPath", label: "主机路径" }
];

const getVolumeTypeDesc = computed(() => {
  switch (volumeType.value) {
    case "PersistentVolumeClaim":
      if (pvcModel.value) {
        return `存储类: ${pvcModel.value.spec?.storageClassName}`;
      } else {
        return "持久卷声明";
      }
    case "ConfigMap":
      return "配置字典";
    case "Secret":
      return "密钥字典";
    case "EmptyDir":
      return "临时卷";
    case "HostPath":
      return "主机路径";
    default:
      return "未知类型";
  }
});

const warningMessage = computed<string>(() => {
  if (isEmpty(volume.value.name)) {
    return "请输入卷名称";
  }

  switch (volumeType.value) {
    case "PersistentVolumeClaim":
      if (
        !pvcModel.value ||
        isEmpty(volume.value?.persistentVolumeClaim?.claimName)
      ) {
        return "请选择持久卷声明";
      }
      break;
    case "ConfigMap":
      if (!cfgMapModel.value || isEmpty(volume.value?.configMap?.name)) {
        return "请选择配置字典";
      }
      break;
    case "Secret":
      if (!secretModel.value || isEmpty(volume.value?.secret?.secretName)) {
        return "请选择密钥字典";
      }
      break;
    case "EmptyDir":
      break;
    case "HostPath":
      break;
    case "Unknown":
      return "请选择存储卷类型";
  }

  return "";
});

const volumeMounts = computed(() => {
  return containers.value?.flatMap(
    container =>
      container.volumeMounts?.filter(
        volumeMount => volumeMount.name === volume.value.name
      ) ?? []
  );
});

const uiState = reactive({
  edit: false
});

onMounted(() => {
  if (!volume.value.name || volume.value.name === "") {
    uiState.edit = true;
  }

  // parseVolumeType();
});
</script>

<template>
  <k-section type="border" collapse>
    <template #head>
      <div class="w-full flex-col">
        <div class="flex items-center w-full gap-3">
          <el-icon size="32"><IconHardDisk /></el-icon>
          <k-desc-item
            :title="volume.name ?? '请编辑名称'"
            :desc="getVolumeTypeDesc"
            class="mr-5"
          />
          <div
            v-if="volumeType === 'PersistentVolumeClaim' && pvcModel"
            class="flex gap-2 flex-1"
          >
            <k-desc-item
              class="flex-grow"
              :title="pvcModel.metadata.name"
              desc="存储卷声明"
            />
            <k-desc-item
              class="flex-grow"
              :title="`${pvcModel.spec?.resources?.requests?.storage ?? '-'}`"
              desc="存储容量"
            />
            <k-desc-item
              class="flex-grow"
              :title="`${pvcModel.spec.accessModes?.join(',') ?? '-'}`"
              desc="访问模式"
            />
          </div>
          <div v-else-if="volumeType === 'ConfigMap'">
            <k-desc-item
              class="flex-grow"
              :title="volume.configMap.name"
              desc="配置字典"
            />
          </div>
          <div v-else-if="volumeType === 'Secret'">
            <k-desc-item
              class="flex-grow"
              :title="volume.secret.secretName"
              desc="保密字典"
            />
          </div>

          <div v-else-if="volumeType === 'EmptyDir'">
            <k-desc-item class="flex-grow" :title="'-'" desc="临时卷" />
          </div>
          <div v-else-if="volumeType === 'HostPath'">
            <k-desc-item
              class="flex-grow"
              :title="volume.hostPath.path"
              desc="主机路径"
            />
          </div>
        </div>
        <el-collapse-transition>
          <div v-if="!isEmpty(warningMessage)" class="volume-warning-msg">
            {{ warningMessage }}
          </div>
        </el-collapse-transition>
      </div>
    </template>
    <div class="w-full">
      <k-section v-if="uiState.edit" title="编辑存储挂载">
        <div class="w-full flex flex-col">
          <k-segment v-model="volumeType" :options="volumeTypeSelections" />
          <el-form :model="volume" label-position="top" class="mt-3">
            <div v-if="volumeType === 'PersistentVolumeClaim'">
              <el-form-item
                required
                label="存储卷"
                prop="persistentVolumeClaim.claimName"
              >
                <PVCSelector
                  v-model="volume.persistentVolumeClaim.claimName"
                  :namespace="namespace"
                  @change="(n, pvc) => (pvcModel = pvc)"
                />
              </el-form-item>
            </div>
            <div v-else-if="volumeType === 'ConfigMap'">
              <el-form-item required label="配置字典" prop="configMap.name">
                <ConfigMapSelector
                  v-model="volume.configMap.name"
                  :namespace="namespace"
                  @change="(n, cfg) => (cfgMapModel = cfg)"
                />
              </el-form-item>
              <k-section
                v-if="cfgMapModel?.data"
                title="配置项"
                type="simple"
                check
                check-on-body
                :check-model="volume.configMap.items?.length ?? 0"
                @check-changed="
                  v => (volume.configMap.items = v ? [{}] : undefined)
                "
              >
                <div
                  v-for="(k, idx) in volume.configMap.items"
                  :key="idx"
                  class="flex w-full gap-3 px-2 mb-5"
                >
                  <ko-data-item
                    v-model="k.key"
                    class="flex-grow"
                    placeholder="请选择数据键名"
                    item-type="flatSelect"
                    :selections="Object.keys(cfgMapModel.data)"
                  />
                  <ko-data-item
                    v-model="k.path"
                    class="flex-grow"
                    item-type="input"
                    placeholder="绑定目录"
                  />
                  <el-button
                    icon="Delete"
                    circle
                    @click="volume.secret.items.splice(idx, 1)"
                  />
                </div>
                <div class="w-full flex justify-end">
                  <el-button
                    circle
                    icon="Plus"
                    @click="volume.configMap.items.push({})"
                  />
                </div>
              </k-section>
            </div>

            <div v-else-if="volumeType === 'Secret'">
              <el-form-item required label="保密字典" prop="secret.secretName">
                <SecretSelector
                  v-model="volume.secret.secretName"
                  :namespace="namespace"
                  @change="(n, secret) => (secretModel = secret)"
                />
              </el-form-item>
              <k-section
                v-if="secretModel?.data"
                title="配置项"
                check
                type="simple"
                check-on-body
                :check-model="volume.secret.items?.length ?? 0"
                @check-changed="
                  v => (volume.secret.items = v ? [{}] : undefined)
                "
              >
                <div
                  v-for="(k, idx) in volume.secret.items"
                  :key="idx"
                  class="flex w-full gap-3 px-2 mb-5"
                >
                  <ko-data-item
                    v-model="k.key"
                    class="flex-grow"
                    placeholder="请选择数据键名"
                    item-type="flatSelect"
                    :selections="Object.keys(secretModel.data)"
                  />
                  <ko-data-item
                    v-model="k.path"
                    class="flex-grow"
                    item-type="input"
                    placeholder="绑定目录"
                  />
                  <el-button
                    icon="Delete"
                    circle
                    @click="volume.secret.items.splice(idx, 1)"
                  />
                </div>
                <div class="w-full flex justify-end">
                  <el-button
                    circle
                    icon="Plus"
                    @click="volume.secret.items.push({})"
                  />
                </div>
              </k-section>
            </div>

            <div v-else-if="volumeType === 'EmptyDir'">
              <el-form-item label="卷名称" required>
                <ko-data-item
                  v-model="volume.name"
                  item-type="input"
                  class="w-full"
                />
              </el-form-item>
            </div>
            <div v-else-if="volumeType === 'HostPath'">
              <el-form-item label="卷名称" required>
                <ko-data-item
                  v-model="volume.name"
                  item-type="input"
                  class="w-full"
                />
              </el-form-item>

              <el-form-item label="主机路径" required>
                <ko-data-item
                  v-model="volume.hostPath.path"
                  class="w-full"
                  item-type="input"
                />
              </el-form-item>
            </div>
          </el-form>
        </div>
      </k-section>

      <k-section type="simple" title="Mounts">
        <ko-volume-mount
          v-for="(c, cidx) in containers"
          :key="`${c.name}_${cidx}`"
          v-model:container="containers[cidx]"
          :volume="volume"
          class="mb-2"
        />
      </k-section>
    </div>
  </k-section>
</template>
<style lang="scss" scoped>
.volume-warning-msg {
  font-size: 12px;
  color: var(--el-color-danger);
}
</style>
